<?php
/**
 * Created by PhpStorm.
 * User: wudiying
 * Date: 2020/2/18
 * Time: 上午12:07
 */


/**
 * swoole进程事件
 *
 * swoole_event_add();
 * 参数1：int $sock
 * int 文件描述符
 * mixed $read_callback 就是stream_socket_client/fsockopen 创建的资源
 * sockets资源，就是sockets扩展中socket_create创建的资源，需要在编译时
 * 加入.configure --enable-sockets
 * 参数2：可读回调函数
 */


$workers = [];//进程池
$worker_num = 3;//进程数量

for ($i = 0; $i < $worker_num; $i++) {
    $process = new swoole_process('doProcess');//创建新进程
    $pid = $process->start();//启动进程并获取进程id
    $workers[$pid] = $process;//放入数组
}

//进程调用的执行函数
function doProcess(swoole_process $process)
{
    $process->write('pid' . $process->pid);   //子进程写入管道pipe
//    echo "写入信息：$process->pid $process->callback"; // 不能访问callback私有变量
    echo "写入信息：$process->pid \n";
}


//添加进程事件，向每一个子进程添加需要执行的动作
foreach ($workers as $process) {
//添加
    swoole_event_add($process->pipe, function ($pipe) use ($process) {
        $data = $process->read();  // 读出信息
        echo '接收到' . $data . "\n";
    });
}